<template>
	<div class="chat-container">
		<!-- 聊天消息区域 -->
		<div class="chat-messages" ref="messagesContainer">
			<div v-for="(message, index) in messages" :key="index" :class="['message', message.sender]">
				<div class="message-content">
					<div class="message-sender">
						{{ message.sender === 'user' ? '你' : '豆包AI' }}
					</div>
					<div class="message-text" v-html="formatMessage(message.text)"></div>
					<div class="message-time">{{ formatTime(message.time) }}</div>
				</div>
			</div>
			<div v-if="isLoading" class="message ai">
				<div class="message-content">
					<div class="message-sender">豆包AI</div>
					<div class="message-text typing">
						<span class="dot"></span>
						<span class="dot"></span>
						<span class="dot"></span>
					</div>
				</div>
			</div>
		</div>

		<!-- 输入区域 -->
		<div class="chat-input">
			<textarea v-model="userInput" @keydown.enter.exact.prevent="sendMessage" placeholder="输入消息..." rows="1"
				ref="inputField"></textarea>
			<button @click="sendMessage" :disabled="!userInput.trim() || isLoading">
				<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
					stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<line x1="22" y1="2" x2="11" y2="13"></line>
					<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
				</svg>
			</button>
		</div>
	</div>
</template>

<script>
	import axios from 'axios';

	export default {
		data() {
			return {
				messages: [{
					sender: 'ai',
					text: '你好！我是豆包AI助手，有什么可以帮你的吗？',
					time: new Date()
				}],
				userInput: '',
				isLoading: false,
				// 豆包API配置
				apiConfig: {
					apiKey: 'a953825e-934c-4ea4-b7f3-156c0ca18515', // 替换为你的API密钥
					apiUrl: 'https://ark.cn-beijing.volces.com/api/v3/chat/completions' // 修正API路径
				},
				errorMessage: null,
				apiError: null
			}
		},
		mounted() {
			this.$nextTick(() => {
				this.scrollToBottom();
				this.$refs.inputField?.focus();
			});
		},
		methods: {
			// 发送消息到豆包API
			async sendMessage() {
				if (!this.userInput.trim() || this.isLoading) return;

				// 添加用户消息到对话
				const userMessage = {
					sender: 'user',
					text: this.userInput,
					time: new Date()
				};

				this.messages.push(userMessage);
				this.userInput = '';
				this.scrollToBottom();
				this.isLoading = true;
				this.errorMessage = null;
				this.apiError = null;

				try {
					// 准备API请求数据
					const messagesForApi = this.messages.map(msg => ({
						role: msg.sender === 'user' ? 'user' : msg.sender === 'ai' ? 'assistant' :
							'system',
						content: msg.text
					}));

					// 调用豆包API
					const response = await axios.post(
						this.apiConfig.apiUrl, {
							model: "doubao-1.5-pro-32k-250115", // 使用正确的模型
							messages: messagesForApi,
							temperature: 0.7,
							max_tokens: 1000
						}, {
							headers: {
								'Content-Type': 'application/json',
								'Authorization': `Bearer ${this.apiConfig.apiKey}`
							}
						}
					);

					// 处理API响应
					const aiResponse = response.data.choices[0].message.content;

					this.messages.push({
						sender: 'ai',
						text: aiResponse,
						time: new Date()
					});

				} catch (error) {
					console.error('豆包API调用错误:', error);
					if (error.response) {
						console.error('错误响应状态码:', error.response.status);
						console.error('错误响应数据:', error.response.data);
					} else if (error.request) {
						console.error('请求未收到响应:', error.request);
					} else {
						console.error('请求配置或其他错误:', error.message);
					}
					this.apiError = error;

					// 显示错误信息
					this.errorMessage = '抱歉，与豆包AI通信时发生错误。请稍后再试。';
					this.messages.push({
						sender: 'system',
						text: this.errorMessage,
						time: new Date()
					});

				} finally {
					this.isLoading = false;
					this.scrollToBottom();
					this.$refs.inputField?.focus();
				}
			},

			// 清除聊天历史
			clearChat() {
				this.messages = [{
						sender: 'system',
						text: 'You are a helpful assistant.',
						time: new Date()
					},
					{
						sender: 'ai',
						text: '你好！我是豆包AI助手，有什么可以帮你的吗？',
						time: new Date()
					}
				];
			},

			// 格式化消息文本（处理换行）
			formatMessage(text) {
				return text.replace(/\n/g, '<br>');
			},

			// 格式化时间显示
			formatTime(date) {
				return date.toLocaleTimeString([], {
					hour: '2-digit',
					minute: '2-digit'
				});
			},

			// 滚动到底部
			scrollToBottom() {
				this.$nextTick(() => {
					if (this.$refs.messagesContainer) {
						this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight;
					}
				});
			}
		},
		watch: {
			// 自动调整输入框高度
			userInput() {
				this.$nextTick(() => {
					if (this.$refs.inputField) {
						this.$refs.inputField.style.height = 'auto';
						this.$refs.inputField.style.height = this.$refs.inputField.scrollHeight + 'px';
					}
				});
			}
		}
	}
</script>

<style scoped>
	/* 样式保持不变 */
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 88vh;
		width: 100%;
		margin: 0;
		background-color: #f5f5f5;
		overflow: hidden;
	}

	.chat-messages {
		flex: 1;
		padding: 12px 8px;
		overflow-y: auto;
		background-color: #f9f9f9;
		-webkit-overflow-scrolling: touch;
	}

	.message {
		margin-bottom: 12px;
		display: flex;
	}

	.message.user {
		justify-content: flex-end;
	}

	.message.ai {
		justify-content: flex-start;
	}

	.message-content {
		max-width: 85%;
		padding: 10px 14px;
		border-radius: 18px;
		position: relative;
		word-break: break-word;
	}

	.user .message-content {
		background-color: #4a6fa5;
		color: white;
		border-bottom-right-radius: 4px;
	}

	.ai .message-content {
		background-color: white;
		color: #333;
		border-bottom-left-radius: 4px;
		box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
	}

	.message-sender {
		font-weight: bold;
		font-size: 0.75rem;
		margin-bottom: 2px;
	}

	.message-text {
		line-height: 1.5;
		font-size: 0.95rem;
	}

	.message-time {
		font-size: 0.65rem;
		opacity: 0.7;
		margin-top: 2px;
		text-align: right;
	}

	.chat-input {
		display: flex;
		padding: 10px;
		background-color: white;
		border-top: 1px solid #eee;
		position: sticky;
		bottom: 0;
		align-items: center;
	}

	.chat-input textarea {
		flex: 1;
		border: 1px solid #ddd;
		border-radius: 20px;
		padding: 12px 16px;
		resize: none;
		max-height: 120px;
		font-family: inherit;
		outline: none;
		font-size: 1rem;
		min-height: 48px;
	}

	.chat-input textarea:focus {
		border-color: #4a6fa5;
	}

	.chat-input button {
		margin-left: 8px;
		background-color: #4a6fa5;
		color: white;
		border: none;
		border-radius: 50%;
		width: 48px;
		height: 48px;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		flex-shrink: 0;
	}

	.chat-input button:disabled {
		background-color: #ccc;
		cursor: not-allowed;
	}

	.typing {
		display: flex;
		align-items: center;
		height: 24px;
	}

	.dot {
		width: 8px;
		height: 8px;
		background-color: #666;
		border-radius: 50%;
		margin: 0 2px;
		animation: bounce 1.4s infinite ease-in-out;
	}

	.dot:nth-child(1) {
		animation-delay: -0.32s;
	}

	.dot:nth-child(2) {
		animation-delay: -0.16s;
	}

	@keyframes bounce {

		0%,
		80%,
		100% {
			transform: translateY(0);
		}

		40% {
			transform: translateY(-6px);
		}
	}

	/* 错误消息样式 */
	.message.system .message-content {
		background-color: #f8d7da;
		color: #842029;
		border-radius: 18px;
		text-align: center;
		margin: 0 auto;
	}

	@media (max-width: 480px) {
		.message-content {
			max-width: 90%;
		}

		.chat-input {
			padding: 8px;
		}

		.chat-input textarea {
			padding: 10px 14px;
			font-size: 0.95rem;
		}

		.chat-input button {
			width: 44px;
			height: 44px;
		}
	}

	@supports (padding-bottom: env(safe-area-inset-bottom)) {
		.chat-container {
			padding-bottom: env(safe-area-inset-bottom);
		}

		.chat-input {
			padding-bottom: calc(10px + env(safe-area-inset-bottom));
		}
	}
</style>